﻿using Furion.CMS.Application;
using Furion.CMS.Core;
using Furion.CMS.Core.Base;
using Furion.CMS.Core.EventSource;
using Furion.EventBus;
using Furion.Logging.Extensions;
using Furion.TaskScheduler;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Furion.CMS.Web.Core
{
    /// <summary>
    /// 消息中心
    /// </summary>
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    public class MessageCenterController : Controller
    {
        /// <summary>
        /// 消息订阅
        /// </summary>
        /// <returns></returns>
        [HttpGet("MessageCenter/Subscribe")]
        [EventSourceExceptionFilter]
        public async Task<string> EventSourceSubscribe([FromServices] IOuterEventHub EventHub, CancellationToken cancellationToken)
        {
            // 按照规范使用事件流内容类型
            HttpContext.Response.ContentType = "text/event-stream";
            HttpContext.Response.Headers["Cache-Control"] = "no-cache";
            HttpContext.Response.Headers["Connection"] = "keep-alive";

            // 从请求标头中获取最后一个事件ID
            int? lastEventId = null;

            if (HttpContext.Request.Headers.TryGetValue("Last-Event-ID", out var lastEventIdString)
                && int.TryParse(lastEventIdString, out var temp))
            {
                lastEventId = temp;
            }

            // 获取发起订阅的远端IP
            string remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "0.0.0.0";

            // 私有事件订阅需加入当前用户标识
            var uId = User.FindFirstValue(AppClaimConsts.UserId);
            // 通道id
            var channelId = Guid.NewGuid();

            // 打开当前请求流进行写入
            // 使用UTF-8编码，并且在处理时不关闭流
            using (var clientStream = new StreamWriter(HttpContext.Response.Body, Encoding.UTF8, 1024, true) { AutoFlush = true })
            {
                // 创建监听
                using (var listener = EventHub.Register(uId, channelId))
                {
                    try
                    {
                        $"Opened event source stream to address: {remoteIp} / channelId: {channelId}".LogInformation();

                        await clientStream.WriteLineAsync($":connected {DateTimeOffset.Now.ToString("o")}");

                        listener.Start();

                        // If a last event id is given, pump out any intermediate events here.
                        if (lastEventId != null)
                        {
                            // We're not doing anything that stores events in this heartbeat demo,
                            // so do nothing here.
                        }

                        // 将事件推入订阅队列时开始输出事件
                        while (listener.State && !cancellationToken.IsCancellationRequested)
                        {
                            var eventInfo = await listener.WaitTrigger(cancellationToken);

                            // 收到事件并推送到客户端
                            if (eventInfo != null)
                            {
                                string updateString = eventInfo.ToString();
                                await clientStream.WriteAsync(new StringBuilder(updateString), cancellationToken);
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        $"客户端 {uId}_{channelId} 断开了与事件源的订阅连接".LogInformation();
                        throw;
                    }
                    catch (Exception e)
                    {
                        $"Closed event source stream from {remoteIp}. Message: {e.Message}".LogError();
                    }
                }
            }

            return ":closed";
        }
    }
}
